module history_mod

  use spark_cubed_sphere
  use params_mod
  use time_mod
  use static_mod
  use state_mod
  use diag_mod
  use tend_mod

  implicit none

  private

  public history_init
  public history_write

contains

  subroutine history_init(static, state, diag, tend)
    type(static_type), intent(in) :: static
    type(state_type ), intent(in) :: state
    type(diag_type  ), intent(in) :: diag
    type(tend_type  ), intent(in) :: tend

    call log_notice('Initialize history file.', pid=proc%id)
    call static%array%create_dataset('h0', file_path=trim(case_name) // '.n' // to_str(nc) // '.nc')
    call state %array%append_dataset('h0')
    call diag  %array%append_dataset('h0')
    call tend  %array%append_dataset('h0')
    
    call fiona_add_att('h0', 'case_id', case_id )
    call fiona_add_att('h0', 'nx'     , nx      )
    call fiona_add_att('h0', 'ny'     , ny      )
    call fiona_add_att('h0', 'dx'     , dx * deg)
    call fiona_add_att('h0', 'dy'     , dy * deg)
    call fiona_add_var('h0', 'tm', 'Total mass'  , '-', dim_names=['time'])
    call fiona_add_var('h0', 'te', 'Total energy', '-', dim_names=['time'])

    call static%array%write('h0', 0._r8, new_file=.true.)

    call time_add_alert('history', seconds=real(history_interval,r8))

  end subroutine history_init

  subroutine history_write(elapsed_seconds, state, diag, tend)
    real(8), intent(in) :: elapsed_seconds
    type(state_type), intent(in) :: state
    type(diag_type ), intent(in) :: diag
    type(tend_type ), intent(in), optional :: tend

    logical new_file
          
    new_file = .false.
    if (time_is_alerted('history')) then
      call log_notice('Write history file.', pid=proc%id)
      call state%array%write('h0', elapsed_seconds, new_file=new_file)
      call diag%array%write('h0', elapsed_seconds, new_file=new_file)
      call fiona_start_output('h0', elapsed_seconds, new_file=new_file)
      call fiona_output('h0', 'tm', diag%tm)
      call fiona_output('h0', 'te', diag%te)
      call fiona_end_output('h0')
      if (present(tend)) call tend%array%write('h0', elapsed_seconds, new_file=new_file)
    end if

  end subroutine history_write

end module history_mod
